//
// Created by ole on 24-8-21.
//

#include "TimerPlugin.h"
#include "../../utils/Log.h"

#include <csignal>

std::shared_ptr<TimerPlugin> TimerPlugin::timerInstance = nullptr;

TimerPlugin::TimerPlugin() : BasePlugin("TimerPlugin", "1.0.0") {
    std::shared_ptr<TimerPlugin> _instance(this, [](const TimerPlugin *pBase) {
        // delete pBase;
    });
    timerInstance = _instance;
}

void TimerPlugin::onTime(const int signal) {
    timerInstance->onTimeInner(signal);
}

void TimerPlugin::onTimeInner(int signal) {
    Log::d(TAG, "onTime().");
    const auto message = std::make_shared<Message>("/core/plugin/TimerPlugin/onTime", "onTimeEvent");
    message->putString("name", "TimerPlugin");
    publishMessage(message);

    if (isStarted()) {
        alarm(5);
    }
}

bool TimerPlugin::onStart() {
    Log::d(TAG, "onStart");
    std::signal(SIGALRM, &TimerPlugin::onTime);
    alarm(5);
    return true;
}

bool TimerPlugin::onStop() {
    Log::d(TAG, "onStop");
    return true;
}
